package com.example.a79273.nvshenyichu;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioGroup;

import com.example.a79273.nvshenyichu.fragment.DaPei;
import com.example.a79273.nvshenyichu.fragment.DanPin;
import com.example.a79273.nvshenyichu.fragment.FaXian;
import com.example.a79273.nvshenyichu.fragment.WoDe;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup radioGroup;
    private FragmentManager fragmentManager;
    private Fragment currentFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        setData();
        setListener();
    }


    private void setListener() {
        radioGroup.setOnCheckedChangeListener(this);
    }

    private void setData() {

    }

    private void initData() {
        fragmentManager = getSupportFragmentManager();
        showAndHideOfFragment(DaPei.class);
    }

    private void initView() {
        radioGroup = (RadioGroup) findViewById(R.id.rg_main_buttons);
    }


    private void showAndHideOfFragment(Class clazz) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment fragmentByTag = fragmentManager.findFragmentByTag(clazz.getSimpleName());
        if (fragmentByTag == null) {
            try {
                fragmentByTag = (Fragment) clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            transaction.add(R.id.fl_main_occupied, fragmentByTag, clazz.getSimpleName());

        }
        if (currentFragment == fragmentByTag) {
            return;
        }
        transaction.show(fragmentByTag);
        if (currentFragment != null) {
            transaction.hide(currentFragment);
        }
        currentFragment = fragmentByTag;

        transaction.commit();
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        Class clazz = null;
        switch (checkedId) {
            case R.id.iv_main_dapei:
                clazz = DaPei.class;
                break;
            case R.id.iv_main_danpin:
                clazz = DanPin.class;
                break;
            case R.id.iv_main_faxian:
                clazz = FaXian.class;
                break;
            case R.id.iv_main_wode:
                clazz = WoDe.class;
                break;
            default:
                break;
        }
        if (clazz != null) {
            showAndHideOfFragment(clazz);
        }
    }
}
